package com.ihr360.excel.validation;

import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.excel.validation.annonation.SpreadSheetValid;
import com.ihr360.excel.vo.CustomSpreadSheetValidateResult;
import com.ihr360.excel.vo.SpreadSheetSpecification;
import com.ihr360.excel.vo.SpreadSheetValidInterruptError;
import com.ihr360.excel.vo.SpreadSheetValidatorRequest;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author richey
 */
public abstract class AbstractSpreadSheetValidateController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 获取当前校验器
     *
     * @param moduleCode
     * @return
     */
    protected SpreadSheetValidator getSpreadSheetValidator(String moduleCode) {
        Map<String, Object> validatorBeans = applicationContext.getBeansWithAnnotation(SpreadSheetValid.class);

        SpreadSheetValidator validator = null;
        for (Object validatorBean : validatorBeans.values()) {
            SpreadSheetValid spreadSheetValid = validatorBean.getClass().getAnnotation(SpreadSheetValid.class);
            if (moduleCode.equals(spreadSheetValid.code())) {
                validator = (SpreadSheetValidator) validatorBean;
                break;
            }
        }
        return validator;
    }

    protected CustomSpreadSheetValidateResult getCustomValidateResult(SpreadSheetValidatorRequest request) {
        CustomSpreadSheetValidateResult result = new CustomSpreadSheetValidateResult();
        SpreadSheetValidator validator = getSpreadSheetValidator(request.getModuleCode());
        if (validator == null) {
            return result;
        }
        try {
            result = validator.customValidate(request);
        } catch (Ihr360Exception exception) {
            SpreadSheetValidInterruptError interruptError = new SpreadSheetValidInterruptError();
            interruptError.setDefaultLogMsg(exception.getMessage());
            interruptError.setLogMsgKey(exception.getMessageKey());
            result.setInterruptError(interruptError);
        }
        return result;
    }

    protected SpreadSheetSpecification getCommonSpecification(SpreadSheetValidatorRequest request) {
        SpreadSheetSpecification result = new SpreadSheetSpecification();

        SpreadSheetValidator validator = getSpreadSheetValidator(request.getModuleCode());
        if (validator == null) {
            return result;
        }
        return validator.commonSpecification(request);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
